package com.dl.chat.client;

import com.google.gson.Gson;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class VectorizationClient {

    private static final String PYTHON_SERVICE_URL = "http://localhost:5000/vectorize";

    private final RestTemplate restTemplate = new RestTemplate();

    /**
     * 调用 Python 服务将文本转化为向量
     *
     * @param text 需要向量化的文本
     * @return 向量数组
     */
    public float[] vectorizeText(String text) {
        try {
            // 构造请求体
            String requestBody = new Gson().toJson(new TextInput(text));

            //构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            //构建HTTPEntity
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            // 发送 POST 请求
            String response = restTemplate.postForObject(PYTHON_SERVICE_URL, entity, String.class);

            // 解析响应
            return new Gson().fromJson(response, VectorResponse.class).embedding;
        } catch (Exception e) {
            throw new RuntimeException("文本向量化失败", e);
        }
    }

    /**
     * 请求体
     */
    static class TextInput {
        String text;

        TextInput(String text) {
            this.text = text;
        }
    }

    /**
     * 响应体
     */
    static class VectorResponse {
        float[] embedding;
    }
}